package com.xiyoukt.springboot.controller;

import com.xiyoukt.springboot.Result;
import com.xiyoukt.springboot.annotation.TestAnnotation;
import com.xiyoukt.springboot.constant.ResultEnum;
import com.xiyoukt.springboot.entity.Test;
import com.xiyoukt.springboot.exception.BusinessException;
import com.xiyoukt.springboot.service.TestService;
import com.xiyoukt.springboot.task.AsyncTask;
import com.xiyoukt.springboot.task.ScheduleTask;
import com.xiyoukt.springboot.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @Autowired
    private AsyncTask asyncTask;

    private Logger log = LoggerFactory.getLogger(ScheduleTask.class);

    @GetMapping("test4")
    public Result<Boolean> test4(String id) throws InterruptedException, ExecutionException {
        ResultUtil<Boolean> resultUtil = new ResultUtil<>();
//        String s = asyncTask.task1();
//        log.info(s);
        // 开始异步调用
        Future<String> future = asyncTask.task2();
        // 进行一些其他的处理，这一部分是异步的
        // 。。。
        log.info("我是异步的哦");
        // 获取结果会阻塞
//        future.
        String s = future.get();
        log.info(s);
        return resultUtil.success(Boolean.TRUE);
    }


    @GetMapping("test3")
    public Result<Test> test3(String id){
        if(id.equals("1")){
            throw new BusinessException(ResultEnum.PARAM_ERROR);
        }

        ResultUtil<Test> resultUtil = new ResultUtil<>();
        Test test = testService.getTest();


//        if(1 == 1){
//            int i = 1 / 0;
//        }
        return resultUtil.success(test);
    }

    @TestAnnotation
    @GetMapping("test")
    public Result<Boolean> test(){
        ResultUtil<Boolean> resultUtil = new ResultUtil<>();
        return resultUtil.success(Boolean.TRUE);
    }

    @GetMapping("test2")
    public Result<Boolean> test2(){
        ResultUtil<Boolean> resultUtil = new ResultUtil<>();
        if(1 == 1){
            throw new RuntimeException("error");
        }
        return resultUtil.success(Boolean.TRUE);
    }

}
